﻿using ClosedXML.Excel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using rehabilitation.Data;
using rehabilitation.Models;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace WebApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ExportController : ControllerBase
    {
        private readonly AppDbContext _context;

        public ExportController(AppDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 导出患者及其医生、随访、康复指导和医患沟通数据
        /// </summary>
        [HttpGet("exportExcel")]
        public async Task<IActionResult> ExportPatientsData()
        {
            var patients = await _context.Patients
                .Include(p => p.DoctorPatientRelations)
                    .ThenInclude(dp => dp.Doctor)
                .Include(p => p.Visits)
                .Include(p => p.Guidances)
                .Include(p => p.Communications)
                .ToListAsync();

            using (var workbook = new XLWorkbook())
            {
                var worksheet = workbook.Worksheets.Add("患者数据");

                // 表头
                worksheet.Cell(1, 1).Value = "患者ID";
                worksheet.Cell(1, 2).Value = "患者姓名";
                worksheet.Cell(1, 3).Value = "性别";
                worksheet.Cell(1, 4).Value = "年龄";
                worksheet.Cell(1, 5).Value = "手机号";
                worksheet.Cell(1, 6).Value = "医生姓名";
                worksheet.Cell(1, 7).Value = "医生手机号";
                worksheet.Cell(1, 8).Value = "随访时间";
                worksheet.Cell(1, 9).Value = "随访内容";
                worksheet.Cell(1, 10).Value = "康复指导内容";
                worksheet.Cell(1, 11).Value = "沟通时间";
                worksheet.Cell(1, 12).Value = "沟通反馈";

                int row = 2;

                foreach (var patient in patients)
                {
                    foreach (var relation in patient.DoctorPatientRelations)
                    {
                        var doctor = relation.Doctor;

                        foreach (var visit in patient.Visits.DefaultIfEmpty(new Visit()))
                        {
                            foreach (var guidance in patient.Guidances.DefaultIfEmpty(new Guidance()))
                            {
                                foreach (var communication in patient.Communications.DefaultIfEmpty(new Communicate()))
                                {
                                    worksheet.Cell(row, 1).Value = patient.Id;
                                    worksheet.Cell(row, 2).Value = patient.Name;
                                    worksheet.Cell(row, 3).Value = patient.Sex;
                                    worksheet.Cell(row, 4).Value = patient.Age;
                                    worksheet.Cell(row, 5).Value = patient.Phone;

                                    worksheet.Cell(row, 6).Value = doctor?.Name ?? "无";
                                    worksheet.Cell(row, 7).Value = doctor?.Phone ?? "无";

                                    worksheet.Cell(row, 8).Value = visit?.Time.ToString("yyyy-MM-dd HH:mm:ss") ?? "无";
                                    worksheet.Cell(row, 9).Value = visit?.Content ?? "无";

                                    worksheet.Cell(row, 10).Value = guidance?.Content ?? "无";

                                    worksheet.Cell(row, 11).Value = communication?.Time.ToString("yyyy-MM-dd HH:mm:ss") ?? "无";
                                    worksheet.Cell(row, 12).Value = communication?.Opinion ?? "无";

                                    row++;
                                }
                            }
                        }
                    }
                }

                // 调整列宽
                worksheet.Columns().AdjustToContents();

                using (var stream = new MemoryStream())
                {
                    workbook.SaveAs(stream);
                    stream.Seek(0, SeekOrigin.Begin);

                    return File(stream.ToArray(),
                                "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                                "PatientsData.xlsx");
                }
            }
        }
    }
}
